﻿//文档就绪函数
$(function () {
    //初始化表格
    ShowWorkerList();
});

//工人列表展示
function ShowWorkerList() {
    layui.use(function () {

        // 点击导出按钮
        document.getElementById('exportBtn').addEventListener('click', function () {
            var checkStatus = table.checkStatus('WorkerListTable');  // 获取当前表格的选中状态
            var selectedData = checkStatus.data;  // 获取选中的数据
            if (selectedData.length === 0) {
                alert('请先选择要导出的数据!');
                return;
            }
            var filteredData = selectedData.map(function (item) {
                // 创建一个新对象，只包含您想要的属性
                return {
                    '工人列表Id': item.workerListId,
                    '工人编号': item.workerNumber,
                    '工人姓名': item.workersName,
                    '手机号码': item.phoneNumber,
                    '性别': item.gender,
                    '部门': item.department,
                    '班组': item.teamsAndGroups,
                    '状态': item.status,
                };
            });
            console.log(filteredData);

            // 使用 XLSX 导出选中的数据
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出为 Excel 文件
            XLSX.writeFile(wb, '工人列表.xlsx');
        });

        var table = layui.table;
        var WorkerNumber = $("#ShowWorkerNumber").val();
        var WorkersName = $("#WorkersName").val();
        var Status = $("#Status").val();

        //执行渲染
        table.render({
            elem: '#WorkerListTable',
            page: {
                limit: 15, //每页显示的条数
                limits: [15, 20, 25, 30] //每页显示条数的选择项
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'workerNumber', title: '工人编号', width: 130 },
                { field: 'workersName', title: '工人姓名', width: 130 },
                { field: 'phoneNumber', title: '手机号码', width: 130 },
                
                {
                    field: 'gender', title: '性别', width: 130,
                    templet: function (d) {
                        // 根据 gender 的值返回对应的性别字符串
                        return d.gender ? '男' : '女';
                    }
                },
                { field: 'department', title: '部门', width: 130 },
                { field: 'teamsAndGroups', title: '班组', width: 130 },
                {
                    field: 'status', title: '状态', width: 130,
                    templet: function (d) {
                        // 根据状态返回不同颜色的字体
                        var statusColor = '';
                        switch (d.status) {
                            case '正常':
                                statusColor = 'style="color: #16b777;"';
                                break;
                            case '离职':
                                statusColor = 'style="color: #ff5722;"';
                                break;
                            default:
                                // 如果状态不是上述任何一个，可以使用默认颜色或不做特殊处理
                                statusColor = '';
                        }
                        // 返回带有样式的状态文本
                        return '<span ' + statusColor + '>' + d.status + '</span>';
                    }
                },
                {
                    field: '', title: '操作', width: 180, templet: function (d) {
                        let status = d.status;
                        let productionExecution = '<a class="layui-btn layui-bg-blue layui-btn-xs" href="javascript:;" onclick="CheckInfo(' + d.workerListId + ')">查看</a>';
                        let pauseButton = '';
                        let closeButton = '';
                        let deleteButton = '';
                        if (status === '离职') {
                            // 为离职状态添加编辑和删除按钮
                            pauseButton = '<a class="layui-btn layui-bg-blue layui-btn-xs" href="javascript:;" onclick="EditProcessTask(' + d.workerListId + ')">编辑</a>';
                            closeButton = '<a class="layui-btn layui-bg-red layui-btn-xs" href="javascript:;" onclick="DeleteWorker(' + d.workerListId + ')">删除</a>';
                        } else if (status === '正常') {
                            // 为正常状态添加编辑和停工按钮
                            pauseButton = '<a class="layui-btn layui-bg-blue layui-btn-xs" href="javascript:;" onclick="EditProcessTask(' + d.workerListId + ')">编辑</a>';
                            deleteButton = '<a class="layui-btn layui-bg-blue layui-btn-xs" href="javascript:;" onclick="Shutdown(' + d.workerListId + ')">停工</a>';
                        }
                        return productionExecution + pauseButton + closeButton + deleteButton;
                    },
                }
            ]],
            //数据接口
            data: []
        });
        //请求数据
        $.ajax({
            url: '../WWHours/GetWorkerList',
            type: "get",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            data: {
                PageIndex: 1,
                PageSize: 15,
                WorkerNumber: WorkerNumber,
                WorkersName: WorkersName,
                Status: Status
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data);
                table.reload('WorkerListTable', {
                    pagge: {
                        limit: 15,
                        limits: [15, 20, 25, 30]
                    },
                    data: data.data.list
                });
            },
            error: function () {
                console.log("请求失败");
            }

        });
    });
}

var obj = {
    WorkerListId:'',
    WorkerNumber: '',
    WorkersName: '',
    PhoneNumber: '',
    Gender: '',
    Department: '',
    TeamsAndGroups: '',
    Status: ''
};

//添加工人
window.AddWorker = function AddWorker() {
    layui.use(['layer', 'form'], function () {
        var layer = layui.layer;
        var form = layui.form;
        layer.open({
            type: 1,
            title: '添加工人信息',
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '500px'],
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumber" name="WorkerNumber" required lay-verify="required" placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersName" name="WorkersName" required lay-verify="required" placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="Gender" value="true" title="男">
                        <input type="radio" name="Gender" value="false" title="女">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block">
                        <select name="Department" style="width:300px">
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">班组</label>
                    <div class="layui-input-block">
                        <select name="TeamsAndGroups">
                            <option value="">请选择班组</option>
                            <option value="一班">一班</option>
                            <option value="二班">二班</option>
                            <option value="三班">三班</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="Status" value="正常" title="正常">
                        <input type="radio" name="Status" value="离职" title="离职">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block" style="text-align:right">
                        <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                        <button class="layui-btn" lay-submit lay-filter="formDemo">添加</button>                 
                    </div>
                </div>
            </form>`,
            success: function (layero, index) { // 添加 index 参数

                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();

                    // 自动生成时间并赋值给工人编号输入框
                    var workerNumberInput = $(layero).find('#WorkerNumber');
                    generateDate(workerNumberInput);
                }, 100);

                // 监听提交
                form.on('submit(formDemo)', function (data) {
                    var field = data.field;
                    var objTwo = {
                        WorkerNumber: field.WorkerNumber,
                        WorkersName: field.WorkersName,
                        PhoneNumber: field.PhoneNumber,
                        Gender: field.Gender,
                        Department: field.Department,
                        TeamsAndGroups: field.TeamsAndGroups,
                        Status: field.Status,
                        CreatedBy:"张三"
                    };

                    $.ajax({
                        url: '../WWHours/AddWorkerList',
                        type: "Post",
                        headers: {
                            "Authorization": localStorage.getItem("token")
                        },
                        data: {
                            dto: objTwo
                        },
                        success: function (res) {
                            var response = JSON.parse(res);
                            if (response.code === 1) {
                                layer.alert("添加成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                layer.msg('添加失败：' + response.message, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg('添加失败,请稍后重试', {
                                time: 2000,
                                icon: 2
                            });
                        }
                    });
                    return false;
                });
                // 添加取消按钮功能
                $(layero).find('.layui-btn-primary').on('click', function () {
                    layer.close(index);
                });
            }
        });
    });
}

// 自动生成时间并赋值给指定的输入框
function generateDate(inputField) {
    var n = new Date();
    var ss = "DB" + n.getFullYear() + (n.getMonth() + 1).toString().padStart(2, '0') +
        n.getDate().toString().padStart(2, '0') +
        n.getHours().toString().padStart(2, '0') +
        n.getMinutes().toString().padStart(2, '0') +
        n.getSeconds().toString().padStart(2, '0');
    if (inputField) {
        inputField.val(ss);
    } else {
        $("#WorkerNumber").val(ss); // 如果不传递inputField，则默认设置到ID为WorkerNumber的元素
    }
}

//查看
layui.use(['table', 'form', 'layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //查看工人信息
    window.CheckInfo = function (workerListId) {
        var token = localStorage.getItem("token");
        //先根据id获取数据
        $.ajax({
            type: "Get",
            headers: {
                "Authorization": token
            },
            url: "../WWHours/ReverseWorkerList",
            data: { WorkerListId: workerListId },
            success: function (res) {
                var data = JSON.parse(res).data;
                console.log(data);
                $("#WorkerListId").val(data.workerListId);
                $("#WorkerNumberCheck").val(data.workerNumber);
                $("#WorkersNameCheck").val(data.workersName);
                $("#PhoneNumber").val(data.phoneNumber);
                $("[name='Gender'][value='" + data.gender + "']").prop('checked', true);
                $("[name='Status'][value='" + data.status + "']").prop('checked', true);
                $("#Department").val(data.department);
                $("#TeamsAndGroups").val(data.teamsAndGroups);
            }
        });
        layer.open({
            type: 1,//iframe层
            title: '查看工人信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['600px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumberCheck" name="WorkerNumberCheck" required lay-verify="required" disabled placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersNameCheck" name="WorkersNameCheck" required lay-verify="required" disabled placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" disabled placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="Gender" value="true" title="男" disabled>
                        <input type="radio" name="Gender" value="false" title="女" disabled>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block" readonly>
                        <select id="Department" name="Department" disabled>
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">班组</label>
                    <div class="layui-input-block" readonly>
                        <select id="TeamsAndGroups" name="TeamsAndGroups" disabled>
                            <option value="">请选择班组</option>
                            <option value="一班">一班</option>
                            <option value="二班">二班</option>
                            <option value="三班">三班</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block" readonly>
                        <input type="radio" name="Status" value="正常" title="正常" disabled>
                        <input type="radio" name="Status" value="离职" title="离职" disabled>
                    </div>
                </div>
            </form>`,
            success: function () {
                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();
                }, 300); // 使用 setTimeout 延迟渲染，确保DOM完全加载
            }
        });
    }
});


//全局变量
//编辑工人信息
layui.use(['table', 'form', 'layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //编辑工人信息--反填+修改
    window.EditProcessTask = function (workerListId) {
        var token = localStorage.getItem("token");
        //先根据id获取数据
        $.ajax({
            type: "Get",
            headers: {
                "Authorization": token
            },
            url: "../WWHours/ReverseWorkerList",
            data: { WorkerListId: workerListId },
            success: function (res) {
                var data = JSON.parse(res).data;
                console.log(data);

                // 直接填充表单和 obj 对象
                $("#WorkerListId").val(data.workerListId);
                $("#WorkerNumberFind").val(data.workerNumber);
                $("#WorkersNameFind").val(data.workersName);
                $("#PhoneNumber").val(data.phoneNumber);
                $("[name='Gender'][value='" + data.gender + "']").prop('checked', true);
                $("[name='Status'][value='" + data.status + "']").prop('checked', true);
                $("#Department").val(data.department); 
                $("#TeamsAndGroups").val(data.teamsAndGroups);
                //存储反填信息到 obj 对象
                obj = {
                    WorkerListId: data.workerListId,
                    WorkerNumberFind: data.workerNumber,
                    WorkersNameFind: data.workersName,
                    PhoneNumber: data.phoneNumber,
                    Gender: data.gender,
                    Status: data.status,
                    Department: data.department,
                    TeamsAndGroups:data.teamsAndGroups,
                    CreatedBy: data.createdBy,
                    CreatedDate: data.createdDate,
                    UpdatedBy: data.updatedBy || '',
                    DeletedBy: data.deletedBy,
                    DeletedDate: data.deletedDate,
                    IsDeleted: data.isDeleted
                };
            }
        });
        layer.open({
            type: 1,//iframe层
            title: '编辑工人信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['600px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumberFind" name="WorkerNumberFind" required lay-verify="required" placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersNameFind" name="WorkersNameFind" required lay-verify="required" placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="Gender" value="true" title="男">
                        <input type="radio" name="Gender" value="false" title="女">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block">
                        <select id="Department" name="Department">
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">班组</label>
                    <div class="layui-input-block">
                        <select id="TeamsAndGroups" name="TeamsAndGroups">
                            <option value="">请选择班组</option>
                            <option value="一班">一班</option>
                            <option value="二班">二班</option>
                            <option value="三班">三班</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="Status" value="正常" title="正常">
                        <input type="radio" name="Status" value="离职" title="离职">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block" style="text-align:right">
                        <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                        <button class="layui-btn" lay-submit lay-filter="demo-update">提交修改</button>       
                    </div>
                </div>
            </form>`,
            success: function () {
                
                var objTwo = {
                    WorkerListId: '',
                    WorkerNumber: '',
                    WorkersName: '',
                    PhoneNumber: '', 
                    Gender:'',
                    Status: '',
                    Department: '',
                    TeamsAndGroups: '',  
                    CreatedBy: '',
                    CreatedDate: '',
                    UpdatedBy: '',
                    DeletedBy: '',
                    DeletedDate: '',
                    IsDeleted: false
                };
                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();
                }, 300); // 使用 setTimeout 延迟渲染，确保DOM完全加载
                //监听提交
                form.on('submit(demo-update)', function (data) {
                    //console.log(data.field);
                    var field = data.field;
                    console.log(field);
                    //修改数据
                    objTwo.WorkerListId = obj.WorkerListId;
                    objTwo.WorkerNumber = field.WorkerNumberFind;
                    objTwo.WorkersName = field.WorkersNameFind ;
                    objTwo.PhoneNumber = field.PhoneNumber;
                    objTwo.Gender = field.Gender;
                    objTwo.Department = field.Department;
                    objTwo.TeamsAndGroups = field.TeamsAndGroups;
                    objTwo.Status = field.Status;
                    objTwo.CreatedBy = obj.CreatedBy;
                    objTwo.CreatedDate = obj.CreatedDate;
                    objTwo.UpdatedBy = "张三";
                    objTwo.DeletedBy = obj.DeletedBy;
                    objTwo.DeletedDate = obj.DeletedDate;
                    objTwo.IsDeleted = obj.IsDeleted;
                    console.log(objTwo);
                    //发送请求
                    $.ajax({
                        url: '../WWHours/UpdateWorkerList',
                        type: "Post",
                        headers: {
                            "Authorization": token
                        },
                        data: { objTwo },
                        success: function (res) {
                            console.log(res);
                            var res = JSON.parse(res);
                            if (res.code === 1) {
                                layer.alert("修改成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                layer.msg('修改失败：' + res.message, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg('修改失败,请稍后重试', {
                                time: 2000,
                                icon: 2
                            });
                        }
                    });
                    //阻止表单跳转
                    return false;
                });
            }
        });
    }
});

//删除工人
window.DeleteWorker = function (id) {
    var token = localStorage.getItem("token");
    var data = JSON.stringify({
        workerListId: id,
        deletedBy: "张三"
    })
    layer.confirm('确定要删除该数据吗？', function (index) {
        $.ajax({
            url: '../WWHours/DeleteWorkerList',
            type: "Post",
            headers: {
                "Authorization": token
            },
            data: { data: data },
            success: function (res) {
                console.log(res);
                var res = JSON.parse(res);
                if (res.code === 1) {
                    layer.msg('删除成功', { icon: 1 });
                    ShowWorkerList();
                } else {
                    layer.msg('删除失败', { icon: 2 });
                }
            },
            error: function () {
                layer.msg('删除失败,请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
}


//停工
function Shutdown(workerListId) {
    layer.confirm('确认停工吗？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        $.ajax({
            url: '../WWHours/UpdateWorkerListStatus',
            type: "Post",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            data: {
                workerListId: workerListId,
                status: "停工",
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.code === 1) {
                    layer.msg("暂停成功", { icon: 2 });
                    //刷新页面
                    ShowWorkerList();
                } else {
                    layer.msg("暂停失败", { icon: 2 });
                }
            },
            error: function () {
                console.log("请求失败");
            }
        });
    }, function () {
        layer.msg('已取消', {
            time: 2000, //2s后自动关闭
            btn: ['知道了']
        });
    });
}